<template>
  <div class="login">
    <!-- 表单 -->
    <el-form class="login__form" :model="form" :rules="rules" ref="form">
      <h2 class="login__form-header">教师登录</h2>
      <el-form-item class="login__form-input" prop="code">
        <el-input class="custom_input" placeholder="请输入工号" size="large" v-model="form.code"></el-input>
      </el-form-item>
      <el-form-item class="login__form-input" prop="pwd">
        <el-input class="custom_input" type="password" @keyup.native.enter="submit" placeholder="请输入密码" size="large" v-model="form.pwd"></el-input>
      </el-form-item>
      <el-button type="primary" class="login__form-button" @click="submit">登录</el-button>
      <p class="login__form-toggle">
        <span class="login__form-toggle-text" @click="toRegisterFn">切换到注册</span>
      </p>
    </el-form>
  </div>
</template>

<script>
export default {
  name: 'login',
  data () {
    return {
      isLogin: true,
      form: {
        code: '',
        pwd: ''
      },
      rules: {
        code: [
          { required: true, message: '请输入工号', trigger: 'blur' },
          { min: 4, max: 4, message: '长度在4个字符', trigger: 'blur' }
        ],
        pwd: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 20, message: '长度在6到20个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    toRegisterFn () {
      this.$router.push('/register')
    },
    submit () {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.$store.dispatch('loginTeacher', {
            code: this.form.code,
            pwd: this.form.pwd
          }).then(res => {
            localStorage.setItem('token', res.data.token)
            localStorage.setItem('userInfo', JSON.stringify(res.data.user))
            this.$message('登录成功')
            this.$router.push('/')
          })
        } else {
          return false
        }
      })
    }
  }
}
</script>

<style>
  @import url(./assets/index.css);
</style>
